package com.wallpaper.weatherwallpaper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AddPictureActivity extends Activity {

	private UserImageAdapter userImageAdapter;
	private GridView addpictureGridview;
	private Bitmap fullBm;
	private String picPathSelected;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_picture);
		
		addpictureGridview=(GridView)findViewById(R.id.addpictureGridview);
		userImageAdapter=new UserImageAdapter(this, getSDPicPath());
		addpictureGridview.setAdapter(userImageAdapter);
		
		addpictureGridview.setOnItemClickListener(new OnItemClickListener(){//监听事件  
        	//点击每个图片出现一个Dialog，点击确定添加到用户图库
         public void onItemClick(AdapterView<?> parent, View view, int position, long id)   
         {  
        	 ImageView fullPic=new ImageView(AddPictureActivity.this);
        	 picPathSelected=userImageAdapter.getUserwallpaperPaths().get(position).toString();
        	 fullBm = BitmapFactory.decodeFile(picPathSelected);
        	 fullPic.setImageBitmap(fullBm);
        	 new AlertDialog.Builder(AddPictureActivity.this)
        	 .setTitle(R.string.app_name)
        	 .setView(fullPic)
        	 .setMessage("确定添加到用户图库？")
        	 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
						addToUserWallpaper(picPathSelected);
				}
				
				private void addToUserWallpaper(String picPathSelected) {
					savePath(picPathSelected);
				}

				private void savePath(String picPathSelected) {
					// TODO Auto-generated method stub
					try {
						FileOutputStream outStream=AddPictureActivity.this.openFileOutput("userwallpaper_path.txt", Context.MODE_APPEND);
						String textToAdd=picPathSelected+"*";
						outStream.write(textToAdd.getBytes());
						outStream.close();
						Toast.makeText(AddPictureActivity.this, "已添加到用户图库", Toast.LENGTH_SHORT).show();
						
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(AddPictureActivity.this, "取消添加", Toast.LENGTH_SHORT).show();
				}
			}).show();

         }  
        });
	}

	private List<String> getSDPicPath() {
		 /* 设定目前所?路径 */
	    List<String> it=new ArrayList<String>();      
	    File f=new File("/sdcard/");  
	    File[] files=f.listFiles();
	    
	    /* 将所有档案叵丈ArrayList中 */
	    for(int i=0;i<files.length;i++)
	    {
	      File file=files[i];
	      if(getImageFile(file.getPath()))
	        it.add(file.getPath());
	    }
	    
		String fileContent="";
		try {
			FileInputStream inStream=AddPictureActivity.this.openFileInput("userwallpaper_path.txt");
			int length=inStream.available();
			byte[] buffer=new byte[length];
			inStream.read(buffer);
			fileContent=EncodingUtils.getString(buffer, "UTF-8");
			inStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String[] paths=fileContent.split("\\*");
		for(int i=0;i<paths.length;i++){
			it.remove(paths[i]);
		}
		
	    return it;
	}
	
	private boolean getImageFile(String fName)
	  {
	    boolean re;
	    
	    /* 取得副檔宅 */
	    String end=fName.substring(fName.lastIndexOf(".")+1,
	                  fName.length()).toLowerCase(); 
	    
	    /* 依附檔宅的类型决定MimeType */
	    if(end.equals("jpg")||end.equals("gif")||end.equals("png")
	            ||end.equals("jpeg")||end.equals("bmp"))
	    {
	      re=true;
	    }
	    else
	    {
	      re=false;
	    }
	    return re; 
	  }
}
